package cn.dckeji.dcssm.service.impl;

import cn.dckeji.dcssm.common.utils.MD5Util;
import cn.dckeji.dcssm.dao.AdminDao;
import cn.dckeji.dcssm.entity.Admin;
import cn.dckeji.dcssm.entity.Users;
import cn.dckeji.dcssm.dao.UsersDao;
import cn.dckeji.dcssm.service.UsersService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Kenny
 * @since 2019-07-31
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersDao, Users> implements UsersService {

    @Resource
    private UsersDao usersDao;
    @Override
    public boolean saveUsers(Users users) {
        //查询登录名重复没
        String adminId = users.getUserId();
        String userPhone = users.getUserPhone();
        int buyNum = users.getBuyNum();
        Users users1 = usersDao.selectOne(new QueryWrapper<Users>().eq("userPhone", userPhone).eq("is_deleted",0));
        if (users1!=null) {
            if (StringUtils.isNotBlank(adminId)) {
                String dataAdminId = users1.getUserId();
                if (dataAdminId.equals(adminId)) {
                    users1.setUserName(users.getUserName());
                    users1.setUserPhone(userPhone);
                    users1.setBuyNum(buyNum);
                    if(StringUtils.isNotBlank(users.getUserPwd())){
                        users1.setUserPwd(MD5Util.MD5Encode(users.getUserPwd(),"utf-8"));
                    }
                    usersDao.updateById(users1);
                    return true;
                }
            }
        }else {
            if (StringUtils.isNotBlank(adminId)) {
                if(StringUtils.isNotBlank(users.getUserPwd())){
                    users.setUserPwd(MD5Util.MD5Encode(users.getUserPwd(),"utf-8"));
                }
                usersDao.updateById(users);
            }else {
                if(StringUtils.isNotBlank(users.getUserPwd())){
                    users.setUserPwd(MD5Util.MD5Encode(users.getUserPwd(), "utf-8"));
                }else{
                    users.setUserPwd(MD5Util.MD5Encode("123456", "utf-8"));
                }
                users.setGmtCreate(LocalDateTime.now());
                usersDao.insert(users);
            }
            return true;
        }
        return false;
    }


    @Override
    public void updateAdminPassword(String userId) {
        Users users = usersDao.selectById(userId);
        users.setUserPwd(MD5Util.MD5Encode("123456", "utf-8"));
        usersDao.updateById(users);
    }


}
